<script setup>
import { ref, onMounted, watch, toRefs } from 'vue'
import { getSongCommentApi, getMvCommentApi, postOrDeleteCommentApi, toCommentPraiseOrCancelApi } from '@/apis/comment'
import { useUserInfoStore } from '@/stores/userInfoStore'
import { useCookieStore } from '@/stores/cookieStore'
import { ElMessageBox, ElMessage } from 'element-plus'
import FullReplyComment from './FullReplyComment.vue'
import bus from '@/utils/bus'

const props = defineProps(['id', 'type'])

const useUserInfo = useUserInfoStore()
const { userInfo } = toRefs(useUserInfo)
const useCookie = useCookieStore()

// 获取到的评论数据
const comment = ref({})

// 封装获取评论的接口
const getSongComment = async () => {
  // 获取歌曲的评论
  if (props.type === 0) {
    const { data } = await getSongCommentApi({
      id: props.id
    })
    comment.value = data
  }
  // 获取 mv 的评论
  if (props.type === 1) {
    const { data } = await getMvCommentApi({
      id: props.id
    })
    comment.value = data
  }
}

onMounted(async () => {
  // 更新评论
  bus.on('updateComment', () => {
    setTimeout(() => { getSongComment() }, 1500)
    // 滚动条回到最新评论的位置
    let top = document.getElementById('newComment').offsetTop
    emit('changeScroll', top)
  })
  // 首次加载评论
  if (!props.id) return
  getSongComment()
})

// 正在播放的歌曲改变时，获取评论
watch(() => props.id, async () => {
  getSongComment()
})

const emit = defineEmits(['changeScroll'])

// 页码改变时，分页获取评论
const handlePage = async (num) => {
  let top = document.getElementById('newComment').offsetTop
  // 获取歌曲的评论  
  if (props.type === 0) {
    const { data } = await getSongCommentApi({
      id: props.id,
      limit: 20,
      offset: num * 20,
      before: null
    })
    emit('changeScroll', top)
    comment.value.comments = data.comments
  }
  // 获取 mv 的评论
  if (props.type === 1) {
    const { data } = await getMvCommentApi({
      id: props.id,
      limit: 20,
      offset: num * 20,
      before: null
    })
    emit('changeScroll', top)
    comment.value.comments = data.comments
  }
}

// 删除自己发表的评论
const deleteComment = (id) => {
  ElMessageBox.confirm(
    '确定要删除当前的评论吗?',
    '删除评论',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: '确定删除当前的评论吗？',
    }
  )
    .then(async () => {
      await postOrDeleteCommentApi({
        t: 0,
        type: props.type,
        id: props.id,
        commentId: id
      })
      setTimeout(() => { getSongComment() }, 1500)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
}

// 回复评论
const isReplyDialog = ref(false)
const replyCommentId = ref('')
const handleReplyComment = (item) => {
  isReplyDialog.value = true
  replyCommentId.value = item
}

// 给评论点赞
const praiseComment = (id, index, type = 'hot') => {
  toCommentPraiseOrCancel({
    commentId: id,
    t: 1,
    msg: '点赞成功',
    index: index,
    isLiked: true,
    likeCount: 1,
    type: type
  })
}

// 取消评论点赞
const cancelPraiseComment = (id, index, type = 'hot') => {
  toCommentPraiseOrCancel({
    commentId: id,
    t: 0,
    msg: '取消点赞成功',
    index: index,
    isLiked: false,
    likeCount: -1,
    type: type
  })
}

// 给评论点赞或取消
const toCommentPraiseOrCancel = async (params) => {
  if (!useCookie.cookie.cookie) return ElMessage('点赞失败，请登录。')
  const { data } = await toCommentPraiseOrCancelApi({
    songId: props.id,
    cid: params.commentId,
    t: params.t,
    type: props.type
  })
  if (data.code === 200) {
    ElMessage({
      type: 'success',
      message: params.msg
    })
    // 更新点赞后的状态（需判断热门评论和最新评论）
    if (params.type === 'hot') {
      comment.value.hotComments[params.index].liked = params.isLiked
      comment.value.hotComments[params.index].likedCount += params.likeCount
    } else {
      comment.value.comments[params.index].liked = params.isLiked
      comment.value.comments[params.index].likedCount += params.likeCount
    }
  } else {
    ElMessage('点赞失败')
  }
}

</script>

<template>
  <div class="full-comment-box">
    <!-- 热门评论 -->
    <h3 v-show="comment.total">全部评论（{{ comment.total }}）</h3>
    <div class="user-comment" v-for="(item, index) in comment.hotComments" :key="item.commentId">
      <img v-lazy-image="item.user.avatarUrl + '?param=200y200'">
      <div class="comment-box">
        <p class="user">{{ item.user.nickname }}</p>
        <p class="comment">{{ item.content }}</p>
        <div class="comment-info">
          <!-- 发布时间 -->
          <div class="time">{{ item.timeStr }}</div>
          <!-- / 发布时间 -->
          <!-- 点赞、回复等操作 -->
          <div class="info">
            <span class="like-count" v-if="item.liked" @click="cancelPraiseComment(item.commentId, index)">
              <i class="iconfont icon-dianzan1"></i>
              {{ item.likedCount }}
            </span>
            <span class="like-count" v-else @click="praiseComment(item.commentId, index)">
              <i class="iconfont icon-dianzan"></i>
              {{ item.likedCount }}
            </span>
            |
            <span class="like-count" @click="handleReplyComment(item.commentId)">
              <i class="iconfont icon-liaotian"></i>
              回复
            </span>
            |
            <i class="iconfont icon-fenxiang"></i>
          </div>
          <!-- / 点赞、回复等操作 -->
        </div>
      </div>
    </div>
    <!-- / 热门评论 -->

    <!-- 最新评论 -->
    <h3 id="newComment" v-show="comment.total">最新评论：</h3>
    <div class="user-comment" v-for="(item, index) in comment.comments" :key="item.commentId">
      <img :src="item.user.avatarUrl + '?param=200y200'" alt="">
      <div class="comment-box">
        <p class="user">{{ item.user.nickname }}</p>
        <p class="comment">{{ item.content }}</p>
        <div class="comment-info">
          <!-- 发布时间、删除评论按钮 -->
          <div class="time">
            {{ item.timeStr }}
            <i class="iconfont icon-shanchu" v-if="userInfo.profile?.userId === item.user.userId"
              @click="deleteComment(item.commentId)"></i>
          </div>
          <!-- / 发布时间、删除评论按钮 -->
          <!-- 点赞、回复等操作 -->
          <div class="info">
            <span class="like-count" v-if="item.liked">
              <i class="iconfont icon-dianzan1" @click="cancelPraiseComment(item.commentId, index, 'all')"></i>
              {{ item.likedCount }}
            </span>
            <span class="like-count" v-else @click="praiseComment(item.commentId, index, 'all')">
              <i class="iconfont icon-dianzan"></i>
              {{ item.likedCount }}
            </span>
            |
            <span class="like-count" @click="handleReplyComment(item.commentId)">
              <i class="iconfont icon-liaotian"></i>
              回复
            </span>
            |
            <i class="iconfont icon-fenxiang"></i>
          </div>
          <!-- / 点赞、回复等操作 -->
        </div>
      </div>
    </div>
    <!-- / 最新评论 -->

    <!-- 分页 -->
    <div class="pagination" v-if="comment.total">
      <el-pagination background layout="prev, pager, next" :pager-count="9" :page-size="20" @current-change="handlePage"
        :total="comment.total" />
    </div>
    <!-- / 分页 -->

    <!-- 回复评论弹窗 -->
    <el-dialog v-model="isReplyDialog" title="查看回复" width="580" :modal="false" :align-center="true">
      <FullReplyComment :commentId="replyCommentId" :id="props.id" :type="props.type" v-if="isReplyDialog" />
    </el-dialog>
    <!-- / 回复评论弹窗 -->
  </div>
</template>

<style scoped lang='scss'>
.full-comment-box {
  margin: 20px auto;

  .name {
    :deep(.el-input) {
      width: 400px;
      background-color: none;
    }
  }

  h3 {
    margin-top: 40px;
    line-height: 40px;
  }

  .user-comment {
    width: 900px;
    display: flex;
    margin: 20px 0px;

    img {
      height: 80px;
      width: 80px;
      border-radius: 8px;
      background-color: #aaa;
    }

    .comment-box {
      margin-left: 15px;

      .user {
        margin-bottom: 5px;
        font-size: 16px;
        color: $primaryColor;
      }

      .comment {
        line-height: 26px;
      }

      .comment-info {
        width: 800px;
        margin-top: 5px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: $assistText;

        .time {
          display: flex;
          align-items: center;

          .icon-shanchu {
            font-size: 22px;
            margin-left: 10px;
            cursor: pointer;
            color: #6e6e6e;
          }
        }

        .info {
          display: flex;
          align-items: center;

          .like-count {
            display: inline-block;
            cursor: pointer;
            font-size: 14px;
            margin: 0px 5px;
            line-height: 20px;
            display: flex;
            align-items: center;
          }

          .icon-dianzan,
          .icon-dianzan1,
          .icon-fenxiang,
          .icon-liaotian {
            font-size: 20px;
            margin: 0px 2px 0px 5px;
          }

          .icon-dianzan1 {
            color: $primaryColor;
          }
        }
      }
    }
  }

  .pagination {
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

:deep(.el-dialog__body) {
  background-color: #f7f7f7;
  padding: 0px;
}
</style>
